/***
 * 脚本依赖;
 * common.js
 * ejs.js
 * $,jQuery
 *
 */
(function ($) {
    var $Table2 = {
        tableSelect: function ($table, destroyBtn, createBtn, options) {
            $table.find('tbody tr').unbind('click').click(function () {
                if ($(this).text() && $(this).text().indexOf('没有找到符合查询条件的数据!') > -1)return;
                if ($(this).hasClass('active')) {
                    destroyBtn && destroyBtn();
                    $(this).removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                } else {
                    if ($(this).data('json')) {
                        createBtn && createBtn(this);
                        var $checkbox = $(this).addClass('active').find('td:first-child input[type=checkbox]');
                        if ($checkbox.length) {
                            $checkbox.attr('checked', true).prop('checked', true);
                            if (!options.multiSelect) $checkbox.closest('tr').siblings('tr').removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                        } else {
                            $(this).addClass('active');
                            if (!options.multiSelect) $(this).closest('tr').siblings('tr').removeClass('active').find('td:first-child input[type=checkbox]').attr('checked', false).prop('checked', false);
                        }
                    }
                }
            })
        },
        'sort': function ($table, search) {
            $table.find('th .fa').unbind('click').click(function (e) {
                var sort = {sortField: '', sortOrder: ''};
                sort.sortField = $(this).data('sort');
                if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
                    sort.sortOrder = 'ASC';
                    $(this)
                        .removeClass('fa-sort-desc fa-sort')
                        .addClass('fa-sort-asc');
                    $(this)
                        .closest('th')
                        .siblings('th')
                        .find('.fa')
                        .removeClass('fa-sort-desc fa-sort-asc')
                        .addClass('fa-sort');
                } else if ($(this).hasClass('fa-sort-asc')) { //asc
                    sort.sortOrder = 'DESC';
                    $(this)
                        .removeClass('fa-sort-asc fa-sort')
                        .addClass('fa-sort-desc');
                    $(this)
                        .closest('th')
                        .siblings('th')
                        .find('.fa')
                        .removeClass('fa-sort-desc fa-sort-asc')
                        .addClass('fa-sort')
                }
                search && search(sort);
            })

        },
        initThead: function () {
            var $tr_ = $('<tr></tr>');
            options.fields.forEach(function (item, index1) {
                if (index1 == 0) {
                    if (options.checkbox || options.radio) {
                        $tr_.append($('<th></th>'));
                    }
                    if (options.seqNum) {
                        $tr_.append($('<th>序号</th>').css({width: 35}));
                    }
                }
                var $th = $('<th>' + item.label + '</th>');
                if (item.enableSort) {
                    $th.append($('<i data-sort="name" class="pull-right fa fa-sort"></i>'));
                }
                $tr_.append($th);
            });

        },
        /***
         * 初始化搜索框
         */
        initSearch: function (options) {
            if ($('input.search').length) {
                return false;
            }
            //basic search
            var $searchType = $('<div class="input-group-btn"></div>'),
                $searchTypeDown = $('<ul class="dropdown-menu" role="menu"></ul>'),
                $searchTypeLabel = $('<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">单位名称 <span class="caret"></span></button>'),
                $searchInput = $('<input type="text" class="form-control search" data-toggle="autocomplete" data-lookup="[&quot;aaa&quot;, &quot;bbb&quot;, &quot;ccc&quot;, &quot;ddd&quot;, &quot;edfa&quot;, &quot;wdasda&quot;, &quot;tueiyhgk&quot;, &quot;vjflcjx&quot;]" placeholder="请输入...">'),
                $searchBtn = $('<span class="input-group-btn"><button class="btn btn-primary search-btn" data-loading-text="查询中..." type="button">查询</button></span>'),
                $searchCtner = $('<div class="input-group pull-left" style="width: 250px;"></div>');
            var $searchSenior = $('<div class="search-senior"></div>'),
                $searchFormInline = $('<div class="form-inline"></div>'),
                length = 0;
            options.fields.forEach(function (item, index) {
                if (item.enableSearch) {
                    length++;
                    var $item = $('<li><a href="#">' + item.label + '</a></li>');
                    var $seniorItem = '';
                    if (item.dateRange) { //日期范围搜索
                        $seniorItem = $('<div class="form-group input-daterange" data-toggle="datepicker" data-date-start-date="' + (item.start || '2017-03-01') + '"' +
                            ' data-date-end-date="' + ((item.end || moment(Date.now()).format('YYYY-MM-DD'))) + '"><label class="sr-only">' + item.label + ':</label>' +
                            '<input type="text" name="' + item.name + 'Start" data-date-size="small" readonly="readonly" class="form-control input-date"' +
                            ' placeholder="' + item.label + '开始日期"' +
                            ' style="width: 125px;">-<input  name="' + item.name + 'End"  readonly="readonly"  data-date-size="small" type="text" class="form-control input-date" ' +
                            ' style="width: 125px;" placeholder="' + item.label + '结束日期" >');
                    } else {
                        $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                        $seniorItem = $('<div class="form-group ><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                    }
                    $item.data('json', item);
                    $searchTypeDown.append($item);
                    $searchFormInline.append($seniorItem.css({marginBottom: '12px'}));
                    $item.unbind('click').click(function () {
                        var $data = $(this).data('json');
                        $searchTypeLabel.html($data.label + ' <span class="caret"></span>').data('json', $data);
                    });
                    if (!$searchTypeLabel.data('json')) { // 未初始化
                        $searchTypeLabel.html(item.label + ' <span class="caret"></span>').data('json', item)
                    }
                }
                if (item.enableFilter) {
                    length++;
                    var $item = $('<li><a href="#">' + item.label + '</a></li>');
                    var $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                        '<select type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">' +
                        item.filters.map(function (item) {
                            return '<option value="' + item.value + '">' + item.label + '</option>';
                        }).join('') +
                        '</select></div>');

                    $item.data('json', item);
                    $searchTypeDown.append($item);
                    $searchFormInline.append($seniorItem.css({marginBottom: '12px'}));
                }
            });
            if (length == 0)return;
            $searchType.append($searchTypeLabel).append($searchTypeDown);
            if (options.complexItems && options.showSearchComplex) {
                options.complexItems.forEach(function (item) {
                    var $seniorItem = '';
                    if (item.dateRange) { //日期范围搜索
                        $seniorItem = $('<div class="form-group input-daterange" data-toggle="datepicker" data-date-start-date="' + (item.start || '2017-03-01') + '"' +
                            ' data-date-end-date="' + ((item.end || moment(Date.now()).format('YYYY-MM-DD'))) + '"><label class="sr-only">' + item.label + ':</label>' +
                            '<input type="text" name="' + item.name + 'Start" data-date-size="small" class="form-control input-date"' +
                            ' placeholder="' + item.label + '开始日期"' +
                            ' style="width: 125px;">-<input  name="' + item.name + 'End"  data-date-size="small" type="text" class="form-control input-date" ' +
                            ' style="width: 125px;" placeholder="' + item.label + '结束日期" >');
                    } else {
                        $seniorItem = $('<div class="form-group"><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                        $seniorItem = $('<div class="form-group ><label class="sr-only">' + item.label + '：</label>' +
                            '<input type="text" class="form-control" name="' + item.name + '" placeholder="' + item.label + '">&nbsp;</div>');
                    }
                    $searchFormInline.append($seniorItem.css({marginBottom: '12px'}));
                })
            }
            $searchBtn.unbind('click').click(function () { // 单项搜索
                var $data = $searchTypeLabel.data('json');
                var obj = {};
                var $lis = $(this).closest('.input-group').find('li');
                $lis.each(function () {
                    var $json = $(this).data('json');
                    obj[$json.name] = ""; // 单项搜索时，过滤非当前项条件干扰
                });
                obj[$data.name] = $searchInput.val();
                obj.page = 1;
                options.search && options.search(obj)
            });

            $searchCtner.append($searchType).append($searchInput).append($searchBtn);

            var $searchSwitch = $('<a class="search-switch pull-left">高级搜索</a>'),
                $search = $('<button type="submit" class="btn btn-primary">搜索</button>'),
                $export = $('<button type="submit" class="btn btn-primary export">导出</button>');
            $searchFormInline.append($search.css({marginBottom: '12px'}));
            $search.unbind('click').click(function () { // 高级搜索
                var search = {};
                $(this).siblings('.form-group').find('input,select').each(function (index, item) {
                    search[item.name] = item.value;
                });
                options.search && options.search(search)
            });
            $searchSenior.hide();
            $searchSenior.append($searchFormInline);
            $searchSwitch.unbind('click').click(function () {
                if ($(this).text().indexOf('高级') > -1) {
                    $(this).text('普通搜索');
                    $searchCtner.hide();
                    $searchSenior.show();
                    $searchSenior.find('input[name=' + $searchTypeLabel.data('json')['name'] + ']').val($searchInput.val())
                } else {
                    $searchCtner.show();
                    $searchSenior.hide();
                    $searchInput.val($searchSenior.find('input[name=' + $searchTypeLabel.data('json')['name'] + ']').val());
                    // $searchSenior.find('input[name='+$searchTypeLabel.data('json')['name']+']').val($searchInput.val())
                    $(this).text('高级搜索')
                }
            });

            $searchSenior.css({padding: '12px 12px 0'});
            $searchFormInline.css({borderBottom: '1px solid #f4f4f4', paddingBottom: '0px'});
            $(options.toolbar).find('.pull-right').append($searchCtner);
            if (length > 1 || options.showSearchComplex) {
                $(options.toolbar).find('.pull-right').append($searchSwitch);
                if (options.showSearchComplex) {
                    $searchSwitch.click().hide();
                }
            }
            if (options.export) {
                var date = new Date();
                $searchFormInline.find('[name=dateStart]').val(getMonthBeginAndEnd().start);
                $searchFormInline.find('[name=dateEnd]').val(getMonthBeginAndEnd().end);
                $export.unbind('click').click(function () {
                    if (options.search) {
                        var search = {};
                        $(this).siblings('.form-group').find('input,select').each(function (index, item) {
                            search[item.name] = item.value;
                        });
                        generateExportUrl(options.search({}, true, true));
                    }
                });
                $searchFormInline.append($export.css({marginBottom: '12px'}));
            }
            $searchFormInline.find('input[type=text]').unbind('keydown').keydown(function (e) { // 高级搜索
                if (e.keyCode == 13) {
                    $search.click();
                }
            });
            $searchCtner.find('input[type=text]').unbind('keydown').keydown(function (e) { // 高级搜索
                if (e.keyCode == 13) {
                    $searchBtn.click();
                }
            });
            $searchSenior.insertBefore($(options.toolbar).closest('.panel-body'));
        },
        initTbody: function (options) {

        },
        initCellData: function (item, rowData, index1, dataArray, options) {
            return (!!item.filter ? item.filter(rowData, dataArray) : ((rowData[options.fields[index1].name] != 0) ? (rowData[options.fields[index1].name] || '-') : rowData[options.fields[index1].name]))
        },
        initCustomColumn: function (options) {
            if ($('[multiple="multiple"]').length)return;
            if (options.fields.length < 5)return;
            var $multiEle = $('<select data-placeholder="自定义列" multiple="multiple"></select>');
            $(options.toolbar).find('.pull-right').append($multiEle);
            var $multi = $multiEle.multiselect($.extend(MULTI_SETTING, {
                onDropdownHide: function (event) {
                    // console.log($multi.multiselect('getSelected'))
                },
                onChange: function (option, selected) {
                    if (!selected) {
                        $('.custom-' + $(option).val()).hide()
                    } else {
                        $('.custom-' + $(option).val()).show()
                    }
                    // console.log($multiEle.val());
                    $.post('/user/setting', {
                        module: window.location.pathname,
                        columns: $multiEle.val().join(',')
                    })
                },
                // onDeselectAll: function() {
                //     alert('onDeselectAll triggered!');
                // }
            }));
            $.post('/user/getSetting', {
                module: window.location.pathname,
            }, function (item_) {
                if (!item_.data) {
                    var options_ = options.fields.map(function (item) {
                        item.value = item.name;
                        item.selected = true;
                        return item;
                    });
                    $multi.multiselect('dataprovider', options_);
                } else {
                    var options_ = options.fields.map(function (item) {
                        item.value = item.name;
                        if (item_.data.columns) {
                            // item_.data.columns = item_.data.columns;
                            if (item_.data.columns.indexOf(item.name) > -1) {
                                item.selected = true;
                                $('.custom-' + item.name).show()

                            } else {
                                item.selected = false;
                                $('.custom-' + item.name).hide()
                            }
                        } else {
                            item.selected = false;
                        }
                        return item;
                    });
                    $multi.multiselect('dataprovider', options_);
                }
            });
        },
        initRowHead: function (options, $tr, length, index) {
            if (options.checkbox) {
                $tr.append($('<td class="vm" rowspan="' + length + '" ><input type="checkbox"/></th>'));
            }
            if (options.radio) {
                $tr.append($('<td class="vm" rowspan="' + length + '"><input type="radio" name="radio"/></th>'));
            }
            if (options.seqNum) {
                $tr.append($('<td class="vm" rowspan="' + length + '">' + (index + 1) + '</th>'));
            }
            return $tr;
        },
        initStyle: function (item) {
            var $td = $('<td>');
            if (item.style instanceof String) {
                $td.attr('style', item.style);
            } else if (item.style instanceof Object) {
                $td.attr('style', item.style);
            }
            $td.addClass('class-' + item.name);
            return $td;
        },
        init: function (options) {
            var $table = $(this);
            initSubPageScroll();
            var $tr_ = $('<tr>'),
                $thead = $('<thead>'),
                $tbody = $('<tbody>');
            if (options.data.length == 0) {
                $table.find('tbody').html(noData(1));
            }
            var $trTotal_ = $('<tr>'), total_ = {};
            options.data.forEach(function (obj, index) {
                if (obj instanceof Array && obj.length > 1) {
                    obj = _.sortBy(obj, 'id');
                    obj.map(function (subDataRow, subDataIndex) {
                        var $tr = $('<tr>');
                        options.fields.forEach(function (item, index1) {
                            var $td = $Table2.initStyle(item);
                            if (index == 0 && subDataIndex == 0) {
                                if (index1 == 0) {
                                    if (options.checkbox) $tr_.append($('<th>'));
                                    if (options.seqNum) $tr_.append($('<th>').html('序号').addClass('su-table-num'));
                                    $trTotal_.append($('<td>').html('合计'));
                                }
                                $trTotal_.append(item.total ? $('<td>').addClass('total-' + item.name) : $('<td>'));
                                var $th = $('<th>' + item.label + '</th>');
                                $th.addClass('custom-' + item.name);
                                if (item.enableSort) {
                                    $th.append($('<i data-sort="' + item._sort + '" class="pull-right fa fa-sort"></i>'));
                                }
                                $tr_.append($th);
                            }

                            if ($('th.custom-' + item.name).length && $('th.custom-' + item.name).css('display') == 'none') $td.hide();
                            if (subDataIndex == 0) {
                                if (item.combine) {
                                    if (index1 == 0) {
                                        $tr = $Table2.initRowHead(options, $tr, obj.length, index);
                                    }
                                    $td.html($Table2.initCellData(item, subDataRow, index1, obj, options));
                                    $td.addClass('vm');
                                    $td.attr('rowspan', obj.length)
                                } else {
                                    $td.html($Table2.initCellData(item, subDataRow, index1, null, options));
                                }
                                $tr.append($td)
                            } else if (subDataIndex != 0 && !item.combine) {
                                $td.html($Table2.initCellData(item, subDataRow, index1, null, options));
                                if ($tr.find('td').length == 0) $td.css({
                                    borderLeft: '1px solid #dddddd',
                                    textAlign: "left"
                                });
                                $tr.append($td);
                            }
                        });
                        if (!subDataIndex) {
                            $tr.data('json', subDataRow).attr('id', subDataRow.id);
                        }
                        $tbody.append($tr);
                    });

                } else {
                    if (obj instanceof Array) obj = obj[0];
                    var $tr = $('<tr></tr>');
                    options.fields.forEach(function (item, index1) {
                        var $td = $('<td  style="' + (item.style || '') + '" >' + (!!item.filter ? item.filter(obj) : ((obj[options.fields[index1].name] != 0) ? (obj[options.fields[index1].name] || '-') : obj[options.fields[index1].name])) + '</td>');
                        if (item.total) {
                            (Object.keys(total_).length == 0) && (total_['initValue'] = item.initValue || 0);
                            total_[item.name] = total_[item.name] ? floatTool.add(total_[item.name] || 0, item.filter(obj)) : item.filter(obj);
                        }
                        item.filterAsync && item.filterAsync(obj, $td);
                        if (index1 == 0) $tr = $Table2.initRowHead(options, $tr, 0, index);
                        if (index == 0) {
                            if (index1 == 0) {
                                if (options.checkbox) $tr_.append($('<th>'));
                                if (options.seqNum) $tr_.append($('<th>').html('序号').addClass('su-table-num'));
                                $trTotal_.append($('<td>合计</td>'));
                            }
                            $trTotal_.append(item.total ? '<td class="total-' + item.name + '"></td>' : '<td></td>')
                            var $th = $('<th>' + item.label + '</th>');
                            $th.addClass('custom-' + item.name);
                            item.enableSort && $th.append($('<i data-sort="' + item._sort + '" class="pull-right fa fa-sort"></i>'));
                            $tr_.append($th);
                        }
                        $td.addClass('custom-' + item.name);
                        if ($('th.custom-' + item.name).length && $('th.custom-' + item.name).css('display') == 'none') $td.hide();
                        $tr.append($td)
                    });
                    $tr.data('json', obj).attr('id', obj.id);
                    $tbody.append($tr);
                }

            });
            if (Object.keys(total_).length > 0) Object.keys(total_).map(function (key) {
                $trTotal_.find('.total-' + key).html(total_[key]);
                $tbody.append($trTotal_)
            });
            if ($table.hasClass('sticky-thead')) return;
            if ($table.data('$table') && $table.find('th').length) {
                $table.find('tbody').replaceWith($tbody);
            } else {
                $table.data('$table', $table);
                $Table2.initSearch(options);
                $Table2.initCustomColumn(options);
                if (options.onlyBody) {
                    $table.find('tbody').replaceWith(options.data.length == 0 ? noData($tr_.find('th:visible').length || 1) : $tbody);
                } else {
                    $table.html('').append($thead.append($tr_)).append(options.data.length == 0 ? noData($tr_.find('th:visible').length || 1) : $tbody);
                }
                $Table2.sort($table, options.search);

            }
            if ($table.data('$table') && $table.find('th').length && options.fixedHeader) {
                //fixedTableHeader();
            }
            options.rendered && options.rendered();
            if (!options.removeLineSelected) {
                $Table2.tableSelect($table, options.destroyBtn, options.createBtn, options);
            }
        },
    };
    $.fn.$Table2 = function (options) {
        var _default = {};
        options = $.extend({}, _default, options || {});
        if (!$.isArray(options.fields) || !options.fields.length) {
            throw new Error('option.field must be array and option.field.length must over 0 !')
        }
        return this.each(function () {
            $Table2.init.call(this, options);
        })
    };
})(jQuery);


